using System.Collections;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Networking;
using UnityEngine.UI;

namespace Jerry.UiFrame
{
    public class JImage : Image, IPointerDownHandler, IPointerUpHandler, IComponent
    {
        public UnityEvent<JImage> onPress;
        public float pressTime = 1f;
        
        public string ImgSrc
        {
            set
            {
                //加载网络上的图片
                if (value.ToLower().StartsWith("http://") || value.ToLower().StartsWith("https://"))
                {
                    CoroutineTool.Instance.StartCoroutine(DownloadImg(value));
                }
                else//加载本地图片
                {
                    sprite = UIConfig.GetLoader().LoadExternal<Sprite>(value);
                }
            }
        }
        
        public void OnPointerDown(PointerEventData eventData)
        {
            Invoke(nameof(OnPress), pressTime);
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            CancelInvoke(nameof(OnPress));
        }

        public void SetVisible(bool bVisible)
        {
            gameObject.SetActive(bVisible);
        }

        public T GetChild<T>(string childName) where T : IComponent
        {
            var comp = transform.Find(childName).GetComponent<IComponent>();
            return (T)comp;
        }

        private IEnumerator DownloadImg(string url)
        {
            var sp = NetImageCache.Instance.Get(url);
            if (sp)
            {
                sprite = sp;
                yield return new WaitForEndOfFrame();
            }

            UnityWebRequest request = UnityWebRequestTexture.GetTexture(url);
            yield return request.SendWebRequest();

            if (request.error != null)
            {
                Debug.Log(request.error);
            }
            
            if (request.result == UnityWebRequest.Result.Success)
            {
                var texture = DownloadHandlerTexture.GetContent(request);
               
                sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero, 1f);
                NetImageCache.Instance.Add(url, sprite);
            }
        }
        
        private void OnPress()
        {
            onPress?.Invoke(this);
        }
    }
}